package com.ruoyi.common.utils;

import cn.hutool.core.util.ArrayUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * base26Utils
 *
 * @author liliangyu
 */
public class Base36Utils {
    /**
     * 36进制 0-9 A-Z
     */
    private static final char[] BASE36 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
    /**
     * 36
     */
    private static final int BASE36_LENGTH = ArrayUtil.length(BASE36);
    /**
     * 字符到索引的映射
     */
    private static final Map<Character, Integer> CHAR_MAP = new HashMap<>();

    static {
        for (int i = 0; i < BASE36_LENGTH; i++) {
            CHAR_MAP.put(BASE36[i], i);
        }
    }

    /**
     * 加密
     *
     * @param num
     * @return
     */
    public static String encode(long num) {
        if (num == 0) {
            return String.valueOf(BASE36[0]);
        }
        final StringBuilder sb = new StringBuilder();
        while (num > 0) {
            sb.append(BASE36[(int) (num % BASE36_LENGTH)]);
            num /= BASE36_LENGTH;
        }
        return sb.reverse().toString();
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static long decode(final String str) {
        long result = 0;
        for (int i = 0; i < str.length(); i++) {
            result = result * BASE36_LENGTH + CHAR_MAP.get(str.charAt(i));
        }
        return result;
    }


}
